package com.ll.notice.Factory.impl;

import com.ll.notice.Factory.HospitalFactory;
import com.ll.notice.entity.SmsNotice;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class JianxiangHospitalFactoryImpl implements HospitalFactory {

    private final static Logger log = Logger.getLogger(JianxiangHospitalFactoryImpl.class);
    @Override
    public void sendSms(SmsNotice smsNotice) {

            String mobile = smsNotice.getReceiverMobile();
            String templateParam = smsNotice.getSmsContent();
            String content = null;
            try {
                content= URLEncoder.encode(templateParam, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // 创建Post请求
            //HttpPost httpPost = new HttpPost("http://jxapi.gdjxjt.cn:87/api/JxMessage/SendMessage?mobile="+mobile+"&TemplateCode=SMS_205408704&TemplateParam="+content+"&SignName=健翔医院");
            HttpPost httpPost = new HttpPost("http://192.168.100.250:80/api/JxMessage/SendMessage?mobile="+mobile+"&TemplateCode=SMS_205408704&TemplateParam="+content+"&SignName=健翔医院");

            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");

            // 响应模型
            CloseableHttpResponse response = null;
            try {
                // 由客户端执行(发送)Post请求
                response = httpClient.execute(httpPost);
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();

                log.info("响应状态为:" + response.getStatusLine());
                if (responseEntity != null) {
                    log.info("响应内容长度为:" + responseEntity.getContentLength());
                    log.info("响应内容为:" + EntityUtils.toString(responseEntity));
                }
            } catch (ParseException | IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 释放资源
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

}
